<?php
/**
 * Created by PhpStorm.
 * User: lizx
 * Date: 2018/2/7
 * Time: 11:09
 */

namespace app\common\Model;

use think\Model;
use think\Db;
use app\api\repository\PayLogRespository;
use app\api\repository\OrderRespository;
use app\api\repository\OrderInfoShaohuoRepository;
use app\api\repository\OrderInfoPayRepository;
use app\api\service\ShaohuoOrderService;
use app\api\controller\Fun;

class Order extends Model
{
    //订单类型
    const SH = 1;
    const ZP = 2;
    const YS = 3;
    const RE = 4;
    const WD = 5;

    // 1等待买家付款，2买家已付款3未支付已取消4已退款5已完成(包括不需支付订单) 6:订单超时
    public static $order_status = [
        'WAIT_PAY_ORDER' => 1,
        'YET_PAY_ORDER' => 2,
        'CANCLE_NOTPAY_ORDER' => 3,
        'REFUND_ORDER' => 4,
        'DOWN_ORDER' => 5,
        'TIMEOUT_ORDER' => 6,
    ];

    public static $orders = array(
        self::SH => 'sh',//捎货
        self::ZP => 'zp',//宅配
        self::YS => 'ys',//云商
        self::RE => 're',//充值
        self::WD => 'tx',//提现
    );

    /**
     *  根据订单号查询订单信息
     */
    public static function getOrderInfoByOrderNumOrId($order_num = null, $order_id = null)
    {
        if ($order_num == null && $order_id == null) {
            return [
                'code' => 'fail',
                'msg' => '订单id或者订单号不能为空',
            ];
        }

        $model = model('app\common\Model\Order');

        if ($order_num == null) {
            $model->where('id', $order_id);
        }

        if ($order_id == null) {
            $model->where('order_num', $order_num);
        }

        $obj = $model->field('uid,id,type')->find();

        if ($obj == null) {//订单不存在
            return [
                'code' => 'fail',
                'msg' => '订单不存在',
            ];
        }
        switch ($obj->getData()['type']) {

            case '1'://捎货
                $info = OrderInfoShaohuoRepository::instance()->getOrderInfoById($obj->getData()['id']);
                $info['code'] = 'success';
                $info['data']['order_type'] = $obj->getData()['type'];
                return $info;
                break;
            case '4'://充值
                $info = OrderInfoPayRepository::instance()->getOrderInfoById($obj->getData()['id']);
                $info['code'] = 'success';
                $info['data']['order_type'] = $obj->getData()['type'];
                return $info;
                break;
            case '5'://人人店订单
                $info = OrderInfoShaohuoRepository::instance()->getOrderInfoById($obj->getData()['id']);
                $info['code'] = 'success';
                $info['data']['order_type'] = $obj->getData()['type'];
                return $info;
                break;
        }
    }

    /**
     * 更新捎货订单状态
     * 主订单表
     * 捎货
     */
    public static function updateShaoHuoOrder($uid, $order_num = null, $order_id = null, $trade_no = '')
    {
        Db::startTrans();
        try {
            //更新用户的余额
            $userbalance = model("app\common\Model\UserBalance");
            $res = $userbalance->where('uid', $uid)->find();
            $userbalance->recharge_balance = $res->recharge_balance;
            $userbalance->where('uid', $uid);
            $userbalance->isUpdate(true)->save();

            //更新主订单
            OrderRespository::instance()->updateOrderPayedStatus($order_num, '', $trade_no);

            //更新捎货订单信息
            OrderInfoShaohuoRepository::instance()->updateOrderPayedStatus($order_num, '', $trade_no);

            //更新捎货流水表信息
            PayLogRespository::instance()->updateOrderPayedStatus($order_num, '', 0);

            //更新捎货物流
            ShaohuoOrderService::instance()->orderAction($order_id, 2, $uid, '');

            Db::commit();
            return [
                'code' => 'success',
                'data' => '',
            ];
        } catch (\Exception $e) {
            Db::rollback();

            return [
                'code' => 'fail',
                'msg' => $e->getMessage(),
            ];
        };
    }

    /**
     * 充值账户异步回调更新的数据
     * @param $order_num
     * @param $trade_no
     * @param $amount 单位为分
     * @return array
     */
    public static function updateRechargeOrder($uid, $order_num, $trade_no, $amount)
    {
        Db::startTrans();
        try {

            //更新主订单
            OrderRespository::instance()->updateOrderPayedStatus($order_num, '', $trade_no);
            WLog('wx_updates_res.txt', '主订单');

            //更新支付订单信息
            OrderInfoPayRepository::instance()->updateOrderPayedStatus($order_num, '', $trade_no);
            WLog('wx_updates_res.txt', '订单详情');


            //更新用户的余额
            $userBalance = UserBalance::getUserBalance($uid);//单位为分
            $res = UserBalance::updateUserBalance($uid, $amount);
            WLog('wx_updates_res.txt', $uid . ':用户余额:' . $res['recharge_balance']);

            //更改流水记录状态
            PayLogRespository::instance()->updateOrderPayedStatus($order_num, '', $userBalance['recharge_balance'] + $amount);
            WLog('wx_updates_res.txt', '流水');
            Db::commit();
            return [
                'code' => 'success',
                'data' => '',
            ];
        } catch (\Exception $e) {
            Db::rollback();
            return [
                'code' => 'fail',
                'msg' => $e->getMessage(),
            ];
        };
    }

    /**
     * 生成唯一订单号
     * @param $order_type
     * @return string
     */
    public static function createOrderNum($order_type)
    {
        return Order::$orders[$order_type] . date("YmdHis") . dechex(date('m'));
    }

}